import java.util.LinkedList;

import java.util.Queue;
public class FIFOPageReplacement {

    public static void main(String[] args) {

        int[] pageRequests = {7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2, 1, 2, 0, 1, 7, 0, 1};

        int numFrames = 4;
        Queue<Integer> frames = new LinkedList<>();

        int pageFaults = 0;

        int totalPageAccesses = pageRequests.length;

        int successfulAccesses = 0;



        for (int page : pageRequests) {

            boolean pageFound = frames.contains(page);

            System.out.print("当前页面请求: " + page + " | ");

            System.out.print("当前帧内容: " + frames + " | ");
            if (!pageFound) {

                if (frames.size() < numFrames) {

                    frames.offer(page);

                    System.out.println("页面 " + page + " 被添加到帧中 -> " + frames);

                } else {

                    int evictedPage = frames.poll();

                    frames.offer(page);

                    System.out.println("页面 " + evictedPage + " 被替换为 " + page + " -> " + frames);

                }

                pageFaults++;

            } else {

                System.out.println("页面 " + page + " 已在帧中");

                successfulAccesses++;

            }
            // 输出分隔线

            for (int i = 0; i < 50; i++) {

                System.out.print("-");

            }

            System.out.println();

        }
        // 计算页面命中率

        double pageHitRate = (double) successfulAccesses / totalPageAccesses;
        System.out.println("\n最终帧内容: " + frames);

        System.out.println("FIFO页面中断次数：" + pageFaults);

        System.out.println("FIFO页面命中率：" + (pageHitRate * 100) + "%");

    }

}